package com.spx.chapter05.transform;

import com.spx.chapter05.pojo.Event;
import com.spx.util.SampleDataUtil;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * create by undeRdoG on  2022-05-01  11:58
 * 凡心所向，素履以往，生如逆旅，一苇以航。
 */
public class SimpleAggTest {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        DataStreamSource<Event> dataSource = env.fromCollection(SampleDataUtil.getSample());

        // 按照姓名分组
        KeyedStream<Event, String> keyedStream = dataSource.keyBy(new KeySelector<Event, String>() {
            @Override
            public String getKey(Event value) throws Exception {
                return value.user;
            }
        });

        /*
        *  按姓名分组，获取时间戳最大的记录，
        *  max 只是会更新聚合的字段，其他的字段使用的是第一条记录的字段
        * */
        SingleOutputStreamOperator<Event> result1 = keyedStream.max("timestamp");

        /*
        *    maxBy 不仅会更新聚合的字段，其他字段的值也用的是当前记录的其他字段
        * */
        SingleOutputStreamOperator<Event> result2 = dataSource.keyBy(data -> data.user).maxBy("timestamp");

        result1.print("max:");
        result2.print("maxBy");

        env.execute();

    }
}
